﻿using Core.Constants;
using Infrastructure.Managers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RhotCMS.Models
{
    public static class CartManager
    {
        private static object _session = HttpContext.Current.Session[ConstantsStore.STR_STORE_CART]; 
        private static Cart _cart;
        private static string _lang;

       
        static CartManager()
        {
            var obj = _session;
            if (obj != null)
            {
                _cart = (Cart)obj;
            }
            else
            {
                _cart = new Cart();
            }
        }

        public static Cart GetCart()
        {
            return _cart;
        }

        public static void SetCart(Cart cart)
        {
            _cart = cart;
            _session = _cart;
        }

        public static void AddToCart(int productId, string lang)
        {
            var existedCartItem = _cart.CartItems.SingleOrDefault(x => x.ProductId == productId);
            if (existedCartItem != null)
            {
                existedCartItem.ProductsCount += 1;
            }
            else
            {
                var product = new StoreManager().GetProductById(lang, productId);
                var cartItem = new Cart.CartItem() { ProductId=productId, CostPerOne=product.Cost, ProductsCount =1 };
                _cart.CartItems.Add(cartItem);
            }

            _session = _cart;
        }
    }

    public class Cart
    {
        public List<CartItem> CartItems { get; set; }

        public int Count
        {
            get
            {
                int count = 0;
                foreach (var cartItem in this.CartItems)
                {
                    count += cartItem.ProductsCount;
                }
                return count;
            }
        }

        public  float Total
        {
            get
            {
                float total = 0;
                foreach (var cartItem in this.CartItems)
                {
                    total += cartItem.Total;
                }
                return total;
            }
        }

        public Cart()
        {
            CartItems = new List<CartItem>();
        }

        public class CartItem
        {
            public int ProductId { get; set; }
            public int ProductsCount { get; set; }
            public float CostPerOne { get; set; }
            public float Total
            {
                get
                {
                    return CostPerOne * ProductsCount;
                }
            }
        }
    }
}